package com.luhuiguo.cms.server.web.template;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.newatlanta.appengine.vfs.provider.GaeVFS;

import freemarker.cache.TemplateLoader;

public class VfsTemplateLoader implements TemplateLoader {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    private String templateLoaderPath;

    public VfsTemplateLoader(String templateLoaderPath) {
        super();
        setTemplateLoaderPath(templateLoaderPath);

        try {
            FileObject templateLoaderDir = GaeVFS.resolveFile("gae://" + getTemplateLoaderPath());
            if (!templateLoaderDir.exists()) {
                templateLoaderDir.createFolder();
            }
        } catch (FileSystemException e) {
            e.printStackTrace();
        }

    }

    public String getTemplateLoaderPath() {
        return templateLoaderPath;
    }

    public void setTemplateLoaderPath(String templateLoaderPath) {
        if (!templateLoaderPath.endsWith("/")) {
            templateLoaderPath += "/";
        }
        this.templateLoaderPath = templateLoaderPath;
    }

    public Object findTemplateSource(String name) throws IOException {
        if (logger.isDebugEnabled()) {
            logger.debug("Looking for FreeMarker template with name [" + name + "]");
        }
        FileObject fileObject = GaeVFS.resolveFile("gae://" + this.templateLoaderPath + name);

        return (fileObject.exists() ? fileObject : null);
    }

    public Reader getReader(Object templateSource, String encoding) throws IOException {
        FileObject fileObject = (FileObject) templateSource;
        try {
            return new InputStreamReader(fileObject.getContent().getInputStream(), encoding);
        } catch (IOException ex) {
            logger.debug("Could not find FreeMarker template: {}" + fileObject.getName());
            throw ex;
        }
    }

    public long getLastModified(Object templateSource) {
        FileObject fileObject = (FileObject) templateSource;
        try {
            return fileObject.getContent().getLastModifiedTime();
        } catch (FileSystemException e) {
            e.printStackTrace();
            return -1;
        }
    }

    public void closeTemplateSource(Object templateSource) throws IOException {
    }

}
